# -*- coding: utf-8 -*-  
#!/usr/bin/python2.7
"""各类表单和表单验证。"""
from web import form 
import md5
import os
from DataService import DataServiceFactory
""" 表单各种验证 """
Validation={
            'email':form.regexp(r"([a-zA-Z0-9_-])+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$", "请输入正确的电子邮箱"),
            'username':form.regexp(r"\w+","用户名格式不对"),
            'password':form.regexp(r".{5,20}$", '密码必须大于5位'),
            'number':form.regexp(r"\d+",'必须为数字'),
            'title':form.regexp(r".{2,40}$",'标题长度不符'),
            'host':form.regexp(r"(http|https)://[a-zA-Z0-9]+(\.[a-zA-Z0-9]+)+/?$","主机格式不符"),
            'keywords':form.regexp(r"[^\s]+(,[^\s]+)*$","输入格式不对[关键字1,关键字2]"),
            'notnull':form.Validator("不能为空", bool),
            'url':form.regexp(r"[a-zA-z]+://[^\s]*","URL格式不符"),
            'link':form.Validator("不能为空", bool),
            }

class FormService(object):
    def __init__(self):
        self.form=None
    def get(self):
        return self.form
    def validate(self):
        return self.form.validates()
    def submit(self,*args,**kw):
        assert 0,'submit must be defined'
    
class FormServiceFactory(object):
    @staticmethod
    def CommentNewFormServiceInstance(*args,**kw):
        return CommentNewFormService(*args,**kw)
    @staticmethod
    def LoginFormServiceInstance(*args,**kw):
        return LoginFormService(*args,**kw)
    @staticmethod
    def BlogUpdateFormServiceInstance(*args,**kw):
        return BlogUpdateFormService(*args,**kw)
    @staticmethod
    def NavigationNewFormServiceInstance(*args,**kw):
        return NavigationNewFormService(*args,**kw)
    @staticmethod
    def NavigationUpdateFormServiceInstance(*args,**kw):
        return NavigationUpdateFormService(*args,**kw)
    @staticmethod
    def AdminUpdateFormServiceInstance(*args,**kw):
        return AdminUpdateFormService(*args,**kw)
    @staticmethod
    def CategoryNewFormServiceInstance(*args,**kw):
        return CategoryNewFormService(*args,**kw)
    @staticmethod
    def CategoryUpdateFormServiceInstance(*args,**kw):
        return CategoryUpdateFormService(*args,**kw)
    @staticmethod
    def ArticleNewFormServiceInstance(*args,**kw):
        return ArticleNewFormService(*args,**kw)
    @staticmethod
    def ArticleUpdateFormServiceInstance(*args,**kw):
        return ArticleUpdateFormService(*args,**kw)
    @staticmethod
    def ImageUploadFormServiceInstance(*args,**kw):
        return ImageUploadFormService(*args,**kw)
#    @staticmethod
#    def CategroyNewFormServiceInstance():
#        return CategroyNewFormService().get

class ImageUploadFormService(FormService):    
    def __init__(self):
        FormService.__init__(self)
        """评论新建表单"""
        newForm = form.Form(
                                      form.File("photoFile", Validation['notnull'],description=u"路径:"),
                                      form.Button("photoSubmit", type="submit", html=u'提交'),
                                    )
        self.form= newForm

    def submit(self):
        import web
        photoInput = web.input(photoFile={})
        photoFile=photoInput['photoFile']
        return DataServiceFactory.ImageServiceInstance().put(photoFile)
    
class CommentNewFormService(FormService):    
    def __init__(self,articleID=None):
        FormService.__init__(self)
        """评论新建表单"""
        newForm = form.Form(
                                      form.Hidden("comment_article_id", Validation['notnull'],description="article ID:",value=articleID),
                                      form.Textbox("comment_nickname", Validation['notnull'],description="昵称:"),
                                      form.Textbox("comment_email",Validation['notnull'],description="邮箱:"),
                                      form.Textbox("comment_website", description="网站:"),
                                      form.Textarea("comment_content",Validation['notnull'], description="内容:"),
                                      form.Button("comment_submit", type="submit", html=u'提交'),
                                    )
        self.form= newForm
    def submit(self):
        articleID=int(self.form.comment_article_id.get_value())
        
        nickname=self.form.comment_nickname.get_value()
        email=self.form.comment_email.get_value()
        website=self.form.comment_website.get_value()
        content=self.form.comment_content.get_value()
        import web
        ip=web.ctx.ip
        
        return DataServiceFactory.CommentServiceInstance().put(
                                                               articleID=articleID, 
                                                               nickname=nickname, 
                                                               email=email, 
                                                               website=website, 
                                                               content=content, 
                                                               ip=ip)

class LoginFormService(FormService):
    """登录表单服务"""
    def __init__(self):
        FormService.__init__(self)
        newForm = form.Form(
                                  form.Textbox("login_username",Validation['username'], description=u"邮箱:"),
                                  form.Password("login_password", Validation['password'],description=u"密码:"),
                                  form.Button("login_submit", type="submit", html=u'登陆'),
                                )
        self.form=newForm
    def submit(self):
        username=self.form.login_username.get_value()
        password='%s' % md5.new(self.form.login_password.get_value()).hexdigest()
        return DataServiceFactory.AdminServiceInstance().login(username, password)
    
class ArticleNewFormService(FormService):
    """ 文章新建表单   """
    def __init__(self):
        categoryDict=[(category.key().id(),category.name) for category in DataServiceFactory.CategroyServiceInstance().all()]
        newForm = form.Form(
                                      form.Textbox("article_title",Validation['notnull'], description=u"标题:"),
                                      form.Textbox("article_shortlink",description=u"短网址:"),
                                      form.Textarea("article_content",  Validation['notnull'],description=u"内容:"),
                                      form.Dropdown("article_display", args=[('1','是'),('0','否')],value='1',description=u"显示:"),
                                      form.Dropdown("article_commentEnable", args=[('1','是'),('0','否')],value='1',description=u"允许评论:"),
                                      form.Dropdown("article_category", args=categoryDict,description=u"分类:"),
                                      form.Textbox("article_tags", description=u"标签:"),
                                      form.Button("article_submit", type="submit", html=u'提交'),
                                    )
        self.form= newForm
    def submit(self):
        title="".join(self.form.article_title.get_value().split())#去空格
        shortlink=self.form.article_shortlink.get_value()
        content=self.form.article_content.get_value()
        display=bool(self.form.article_display.get_value())
        
        commentEnable=bool(self.form.article_commentEnable.get_value())
        categoryID=int(self.form.article_category.get_value())
        tagStr=self.form.article_tags.get_value()
        return DataServiceFactory.ArticleServiceInstance().put(
                                                               title=title, 
                                                               shortlink=shortlink,
                                                               content= content,
                                                               categoryID= categoryID,
                                                               tagStr= tagStr,
                                                               display= display,
                                                               commentEnable= commentEnable)

class ArticleUpdateFormService(FormService):
    """ 文章更新表单"""
    def __init__(self,articleID):
        article=DataServiceFactory.ArticleServiceInstance().get(articleID=articleID)
        categoryDict=[(category.key().id(),category.name) for category in DataServiceFactory.CategroyServiceInstance().all()]
        updateForm = form.Form(
                                      form.Hidden("article_id",value=article.key().id()),
                                      form.Textbox("article_title", Validation['notnull'],description=u"标题:",value=article.title),
                                      form.Textbox("article_shortlink",description=u"短网址:",value=article.shortlink),
                                      form.Textarea("article_content", Validation['notnull'], description=u"内容:",value=article.content),
                                      form.Dropdown("article_display", args=[('1','是'),('0','否')],description=u"显示:",value=article.display and "1" or "0"),
                                      form.Dropdown("article_commentEnable", args=[('1','是'),('0','否')],description=u"允许评论:",value=article.display and "1" or "0"),
                                      form.Dropdown("article_category", args=categoryDict,description=u"分类:",value=article.category.key().id()),
                                      form.Button("article_submit", type="submit", html=u'提交'),
                                    )
        self.form = updateForm
    def  submit(self):
        articleID=int(self.form.article_id.get_value())
        title="".join(self.form.article_title.get_value().split())#去空格
        shortlink=self.form.article_shortlink.get_value()
        content=self.form.article_content.get_value()
        display=bool(self.form.article_display.get_value())
        commentEnable=bool(self.form.article_commentEnable.get_value())
        categoryID=int(self.form.article_category.get_value())

        return DataServiceFactory.ArticleServiceInstance().update(
                                                                  articleID=articleID,
                                                                  title=title,
                                                                  shortlink=shortlink,
                                                                  content=content,
                                                                  display=display,
                                                                  commentEnable=commentEnable,
                                                                  categoryID=categoryID)
class BlogUpdateFormService(FormService):
    """ 博客信息更新表单"""
    def __init__(self):
        def getThemesDirDict(relativePath):
            themesDirDict=[]
            dirAbsPath=os.path.abspath(
                              os.path.normpath(relativePath)
                              )
            dirlist=os.listdir(dirAbsPath)
            for dir in dirlist:
                path=os.path.join(dirAbsPath,dir)
                if os.path.isdir(path):
                    themesDirDict.append((dir,dir))
            return themesDirDict
        
        blog=DataServiceFactory.BlogServiceInstance().get()
        newForm = form.Form(
                                      form.Textbox("blog_name", Validation['notnull'], description=u"名称:",value=blog.name),
                                      form.Textbox("blog_title", Validation['notnull'], description=u"标题:",value=blog.title),
                                      form.Textbox("blog_subtitle", Validation['notnull'],  description=u"子标题:",value=blog.subtitle),
                                      form.Textbox("blog_bloger", Validation['notnull'], description=u"博主昵称:",value=blog.bloger),
                                      form.Textbox("blog_email", Validation['email'], description=u"博主email:",value=blog.email),
                                      form.Dropdown("blog_theme", args=getThemesDirDict('themes'),description=u"主题:",value=blog.theme),
                                      form.Textarea("blog_description", Validation['notnull'], description=u"描述:",value=blog.description),
                                      form.Textbox("blog_keywords", Validation['keywords'],description=u"关键字:",value=blog.keywords), 
                                      form.Textarea("blog_announcement",description=u"公告:",value=blog.announcement),
                                      form.Textbox("blog_pageSize", Validation['number'],description=u"每页显示条数:",value=blog.pageSize),
                                      form.Button("blog_submit", type="submit", html=u'提交'),
                                    )
        self.form = newForm
    def submit(self):
        name=self.form.blog_name.get_value()
        title=self.form.blog_title.get_value()
        subtitle=self.form.blog_subtitle.get_value()
        bloger=self.form.blog_bloger.get_value()
        email=self.form.blog_email.get_value()
        theme=self.form.blog_theme.get_value()
        description=self.form.blog_description.get_value()
        keywords=self.form.blog_keywords.get_value()
        announcement=self.form.blog_announcement.get_value()
        pageSize=int(self.form.blog_pageSize.get_value())
        
        return DataServiceFactory.BlogServiceInstance().update(
                                                     name=name,
                                                     title=title,
                                                     subtitle=subtitle,
                                                     bloger=bloger,
                                                     email=email,
                                                     theme=theme,
                                                     description=description,
                                                     keywords=keywords,
                                                     announcement=announcement,
                                                     pageSize=pageSize)

class CategoryNewFormService(FormService):
    """ 分类新建表单 """
    def __init__(self):
        newForm = form.Form(
                                      form.Textbox("category_name",  Validation['notnull'],description=u"分类名称:"),
                                      form.Button("category_submit", type="submit", html=u'提交'),
                                      )
        self.form= newForm
    def submit(self):
        categoryName=self.form.category_name.get_value()
        return DataServiceFactory.CategroyServiceInstance().put(categoryName)


class CategoryUpdateFormService(FormService):
    """分类更新表单"""
    def __init__(self,categoryID):
        category=DataServiceFactory.CategroyServiceInstance().get(categoryID=categoryID)
        updateForm = form.Form(
                                       form.Hidden("category_id",value=category.key().id()),
                                       form.Textbox("category_name",Validation['notnull'],description=u"分类名称:",value=category.name),
                                       form.Button("category_submit",type="submit",html=u'提交'),
                                       )
        self.form = updateForm
    def submit(self):
        categoryID=int(self.form.category_id.get_value())
        name=self.form.category_name.get_value()
        return DataServiceFactory.CategroyServiceInstance().update(
                                                                   categoryID=categoryID,
                                                                   name=name)

class NavigationNewFormService(FormService):
    def __init__(self):
        """导航新建表单"""
        newForm = form.Form(
                                      form.Textbox("navigation_name",  Validation['notnull'],description=u"名称:"),
                                      form.Textbox("navigation_link",  Validation['notnull'],description=u"链接:"),
                                      form.Textbox("navigation_weight", Validation['notnull'],description=u"优先级"),
                                      form.Dropdown("navigation_position",args=[('TOP','顶部'),('SIDE','侧边')],description=u"位置"),
                                      form.Button("navigation_submit", type="submit", html=u'提交'),
                                      )
        self.form = newForm
    def submit(self):
        name=self.form.navigation_name.get_value()
        link=self.form.navigation_link.get_value()
        weight=int(self.form.navigation_weight.get_value())
        position=self.form.navigation_position.get_value()
        return DataServiceFactory.NavigationServiceInstance().put(
                                                                  name=name,
                                                                  link=link,
                                                                  weight=weight,
                                                                  position=position
                                                                  )
class NavigationUpdateFormService(FormService):
    def __init__(self,navigationID):
        navigation=DataServiceFactory.NavigationServiceInstance().get(navigationID=navigationID)
        """ 导航更新表单 """
        updateForm = form.Form(
                                      form.Hidden("navigation_id",value=navigation.key().id()),
                                      form.Textbox("navigation_name", Validation['notnull'],description=u"名称:",value=navigation.name),
                                      form.Textbox("navigation_link", Validation['notnull'],description=u"链接:",value=navigation.link),
                                      form.Textbox("navigation_weight",Validation['notnull'],description=u"优先级",value=navigation.weight),
                                      form.Dropdown("navigation_position",args=[('TOP',u'顶部'),('SIDE',u'侧边')],description=u"位置",value=navigation.position),
                                      form.Button("navigation_submit", type="submit", html=u'提交更新'),
                                      )
        self.form = updateForm
    def submit(self):
        navigationID=int(self.form.navigation_id.get_value())
        name=self.form.navigation_name.get_value()
        link=self.form.navigation_link.get_value()
        weight=int(self.form.navigation_weight.get_value())
        position=self.form.navigation_position.get_value()
        return DataServiceFactory.NavigationServiceInstance().update(
                                                                     navigationID=navigationID,
                                                                     name=name,
                                                                     link=link,
                                                                     weight=weight,
                                                                     position=position
                                                                  )
        
class AdminUpdateFormService(FormService):
    def __init__(self):
        """ 管理员账号更新表单
    
            administrator_old_username                                    原邮箱
            administrator_old_password                           原密码
            administrator_username                                            新邮箱
            administrator_password                                    新密码
            administrator_password_confirm                   确认密码
            administrator_submit                                          提交
        """
        administrator= DataServiceFactory.AdminServiceInstance().get()
        updateForm = form.Form(
                               form.Textbox("administrator_old_username",readonly="true", description=u"原用户名:",value=administrator.username),
                               form.Password("administrator_old_password",Validation['password'],description=u"原密码:"),
                               form.Textbox("administrator_username",Validation['username'],description=u"新用户名:"),
                               form.Password("administrator_password", Validation['password'],description=u"新密码:"),
                               form.Password("administrator_password_confirm", Validation['password'],description=u"确认密码:"),
                               form.Button("administrator_submit", type="submit", html=u'提交'),
                               validators = [
                                             form.Validator(u"确认密码不正确", lambda i: i.administrator_password == i.administrator_password_confirm),
                                             form.Validator(u"原始用户密码不正确",lambda i:DataServiceFactory.AdminServiceInstance().verify(i.administrator_old_username,
                                                                                                                                  '%s' % md5.new( i.administrator_old_password ).hexdigest() ))],
                               )
        self.form = updateForm
    def submit(self):
        """通过 修改密码表单 修改密码"""
        username=self.form.administrator_username.get_value()
        password='%s' % md5.new(self.form.administrator_password.get_value()).hexdigest()
        return DataServiceFactory.AdminServiceInstance().update(username, password)